<template>
  <div class="app-container">

    <div class="content">
      <!-- 头部切换区域 -->
      <div class="toggle-btn">
        <div class="toggle-btn-item" :class="toggle_current==1? 'isactive':'disactive' " @click="handleToggle(1)">
          <i class="iconfont icon-ic_shexiangtou" />
          <span>实时</span>
        </div>
        <div class="toggle-btn-item" :class="toggle_current==0? 'isactive':'disactive' " @click="handleToggle(0)">
          <i class="iconfont icon-icon_list_huifang" />
          <span>回放</span>
        </div>
      </div>
      <!-- 视频播放区域 -->
      <div class="video" />
      <!-- 控件区域 -->
      <div class="control">
        <div class="screen-cut">
          <span class="screen-cut-item">单屏幕</span>
          <span class="screen-cut-item">4屏幕</span>
          <span class="screen-cut-item">9屏幕</span>
          <span class="screen-cut-item">16屏幕</span>
        </div>

        <!-- 调声音和快进按钮 -->
        <div class="screen-btn">
          <span class="screen-btn-item btn-top el-icon-caret-top" />
          <div>
            <span class="screen-btn-item btn-left el-icon-caret-left" />
            <span class="screen-btn-item btn-right el-icon-caret-right" />
          </div>
          <span class="screen-btn-item btn-bottom el-icon-caret-bottom" />
        </div>

        <div class="screen-scale">
          <span class="screen-scale-item"><i class="iconfont icon-jia1" />放大</span>
          <span class="screen-scale-item"><i class="el-icon-minus" style="margin-right: 5px;" />缩小</span>
        </div>
      </div>

      <!-- drawer 抽屉区域 -->
      <div class="drawer-expand">
        <div class="out-in el-icon-arrow-left" @click="handleLeft" />
      </div>
      <el-drawer title="我是标题" :visible.sync="drawer" direction="rtl" size="180px" :modal="false"
        :wrapper-closable="false">

        <template slot="title">
          <span class="drawer-title">设备树</span>
        </template>
        <div class="drawer-con">
          <el-tree :data="data_tree" :props="defaultProps" @node-click="handleNodeClick" />
        </div>
      </el-drawer>
    </div>

  </div>
</template>

<script>
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime
  } from '@/utils' // 解析时间
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {
    delAdmin,
    addAdmin,
    editAdmin,
    listAdmin,
    toggleAdmin,
    listRole
  } from '@/api/system'
  import {
    validPass
  } from '@/utils/validate'
  import {
    logger
  } from 'runjs/lib/common'
  const calendarTypeOptions = [{
      key: 'CN',
      display_name: 'China'
    },
    {
      key: 'US',
      display_name: 'USA'
    },
    {
      key: 'JP',
      display_name: 'Japan'
    },
    {
      key: 'EU',
      display_name: 'Eurozone'
    }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'Storage',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        // if (!validPass(value) && (value && value.length != 64)) {
        if (!validPass(value)) {
          callback(new Error('8~16位,包含大小写字母和数字, 可以有特殊字符'))
        } else {
          callback()
        }
      }

      return {
        data_tree: [{
            label: '一级 1',
            children: [{
              label: '二级 1-1',
              children: [{
                label: '三级 1-1-1'
              }]
            }]
          },
          {
            label: '一级 2',
            children: [{
              label: '二级 2-1',
              children: [{
                label: '三级 2-1-1'
              }]
            }, {
              label: '二级 2-2',
              children: [{
                label: '三级 2-2-1'
              }]
            }]
          },
          {
            label: '一级 3',
            children: [{
              label: '二级 3-1',
              children: [{
                label: '三级 3-1-1'
              }]
            }, {
              label: '二级 3-2',
              children: [{
                label: '三级 3-2-1'
              }]
            }]
          }
        ],
        defaultProps: {
          children: 'children',
          label: 'label'
        },

        drawer: false, // 抽屉
        toggle_current: 1, // 实时和回放  切换值,  1实时
        space_info: {
          name: '默认名',
          id: 34554,
          device_amount: 786656,
          online: 4534,
          create_time: new Date()
        },
        list_device: [{
          deviceId: 1,
          deviceName: 'a111'
        }, {
          deviceId: 1,
          deviceName: 'a222'
        }, {
          deviceId: 1,
          deviceName: 'a333'
        }],
        list_space: [{
          spaceId: 1,
          spaceName: 'a111'
        }, {
          spaceId: 1,
          spaceName: 'a222'
        }, {
          spaceId: 1,
          spaceName: 'a333'
        }],
        going_status: [{
          text: '在线',
          value: 1
        }, {
          text: '离线',
          value: 0
        }],

        multipleSelection: [],
        is_multip: false, // 是否批量 解绑
        tableKey: 0,
        list: null,
        total: 0, // 总条数
        listLoading: true,
        listQuery: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: '' // 搜索关键字
        },
        calendarTypeOptions,
        statusOptions: ['published', 'draft', 'deleted'], // 角色
        temp: {
          id: undefined,
          userName: '',
          password: '',
          again_pass: '',
          status: '',
          role: ''
        },
        old_pass: '', // 原密码
        dialogFormVisible: false,
        dialogStatus: '',
        del_id: '',
        del_index: null,
        dialogPvVisible: false, //  解绑提示框
        dialogToggle: false, // 状态更改的提示框
        rules: {
          password: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }],
          userName: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }],
          again_pass: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }]
        },
        list_role: [], // 获取角色和角色id的 列表
        toggle_id: '', //
        toggle_status: '', // 要切换的状态值
        password_type_reg: 'password',
        password_type_reg2: 'password',
        reg_tooltip: false, // 大写 ?
        reg2_tooltip: false, // 大写 ?
        status_index: '' // 在tab列表页面,, 要切换状态值的  下标
      }
    },
    watch: {
      dialogFormVisible: {
        handler(val, oldval) {
          if (val) {
            this.getListRole() // 获得角色列表
          }
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      // 点击某一个节点
      handleNodeClick(data) {
        console.log(data)
      },
      // 点击显示抽屉
      handleLeft() {
        this.drawer = true
      },
      // 切换 实时/回放
      handleToggle(num) {
        if (num == 0) {
          this.$router.replace({
            path: '/video/playback'
          })
        }
      },
      // 从某个空间的设备列表 返回 所有空间列表
      handleSpace() {
        this.$router.replace({
          path: '/device/space'
        })
      },
      // 确认修改
      editConfirm(row) {
        row.edit = !row.edit
        if (!row.edit) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        }
      },

      // 取消修改 table行内属性
      cancelEdit(row) {
        row.userName = row.originalName
        row.edit = false
        this.$message({
          message: '已取消!',
          type: 'danger'
        })
      },
      // 获取 table 列表
      getList() {
        this.listLoading = true
        listAdmin(this.listQuery.page, this.listQuery.limit, this.listQuery.keyword).then(res => {
          this.list = res.data.records
          this.list = this.list.map(v => {
            this.$set(v, 'edit', false)
            v.originalName = v.userName
            return v
          })
          this.total = parseInt(res.data.total)

          setTimeout(() => {
            this.listLoading = false
          }, 1 * 1000)
        })
      },
      // 点击了 状态值切换
      changeStatus(id, status, index) {
        this.status_index = index
        this.toggle_id = id
        this.toggle_status = status
        this.dialogToggle = true
      },
      // 确认了  状态值切换
      toggleStatus() {
        toggleAdmin(this.toggle_id, this.toggle_status).then(res => {
          this.$notify({
            title: '成功',
            message: '状态修改成功',
            type: 'success',
            duration: 4000
          })
          // this.$message({
          //   message: "状态更改成功!",
          //   type: 'success',
          //   duration: 4000,
          //   showClose: true,
          //   center: true,
          // })
          this.getList() // 重新渲染页面
          this.dialogToggle = false
        })
      },
      // 获取角色列表
      getListRole() {
        listRole(1, 49, '').then(res => {
          this.list_role = res.data.records
        })
      },
      // 监听是否打开了大写
      checkCapslock(num, e) {
        const {
          key
        } = e
        if (num == 0) { // 注册账号: 设置密码
          this.reg_tooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z') // 若开启大写则提示文字
        } else if (num == 1) { // 注册账号: 再次输入密码
          this.reg2_tooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z') // 若开启大写则提示文字
        }
      },
      // 是否显示密码
      showPwd(num) {
        if (num == 0) {
          this.password_type_reg === 'password' ? this.password_type_reg = '' : this.password_type_reg = 'password'
          this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg.focus()
          })
        } else if (num == 1) {
          this.password_type_reg2 === 'password' ? this.password_type_reg2 = '' : this.password_type_reg2 = 'password'
          this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg2.focus()
          })
        }
      },
      // 取消状态管理
      handleCancel() {
        this.getList() // 重新渲染页面
        this.dialogToggle = false
      },
      // 点击了 '编辑' 或添加======================================================
      handleUpdate(row, str) {
        // if (str == 'create') this.resetTemp() // 清空
        if (str == 'create') {
          this.$router.push({
            path: '/device/add_device'
          })
        }
        if (str == 'update') {
          this.$router.push({
            path: '/device/add_device'
          })
          // this.temp = Object.assign({}, row) // 克隆一个对象
          // this.old_pass = this.temp.password
          // this.temp.password = ''   // 不回显密码
        }
        this.dialogStatus = str

        // this.dialogFormVisible = true
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].clearValidate()
        // })
      },
      // 编辑: 确认更新数据
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // if(this.temp.password == this.old_pass){   // 修改了但是没改密码
            //   editAdmin(this.temp.id, '', this.temp.roleId, this.temp.status, this.temp.userName).then(() => {
            //     // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
            //     // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
            //     this.getList()
            //     this.dialogFormVisible = false
            //     this.$notify({
            //       title: '成功',
            //       message: '更新成功',
            //       type: 'success',
            //       duration: 4000
            //     })
            //   })
            // }
            if (this.temp.password == this.temp.again_pass) { // 修改的内容包括: 密码
              const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
              editAdmin(this.temp.id, cryptograph, this.temp.roleId, this.temp.status, this.temp.userName).then(
                () => {
                  // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
                  // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
                  this.getList()
                  this.dialogFormVisible = false
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 4000
                  })
                })
            } else {
              this.$message({
                message: '两次密码输入不一致!',
                type: 'error',
                duration: 4000,
                showClose: true,
                center: true
              })
            }
          }
        })
      },
      // 确认添加了一个管理员
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.temp.password != this.temp.again_pass) {
              this.$message({
                message: '两次密码输入不一致!',
                type: 'error',
                duration: 4000,
                showClose: true,
                center: true
              })
            } else {
              const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
              // let data2 = Object.assign({}, this.temp)   // 克隆一个对象

              addAdmin(cryptograph, this.temp.roleId, 1, this.temp.userName).then(() => {
                // this.list.unshift(this.temp)
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 4000
                })
              })
            }
          }
        })
      },
      // 清空temp
      resetTemp() {
        this.temp = {
          id: undefined,
          userName: '',
          password: '',
          again_pass: '',
          status: 1,
          role: ''
        }
      },
      // 点击了 解绑===============================================
      handleDelete(row, index) {
        this.is_multip = false
        this.del_id = row.id
        this.del_index = index
        this.dialogPvVisible = true
      },
      // 点击了 批量 解绑
      handleDelmultip() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: '没有被选项!',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true
          })
        } else {
          this.is_multip = true
          this.dialogPvVisible = true
        }
      },
      // 确认了 解绑
      delData() {
        let ids = []
        if (this.is_multip) { // 批量 解绑
          this.multipleSelection.forEach((item, i) => {
            ids.push(item.id)
          })
          // ids = this.multipleSelection
        } else {
          ids = [this.del_id]
        }
        this.dialogPvVisible = false
        this.$notify({
          title: '成功',
          message: ' 解绑成功',
          type: 'success',
          duration: 4000
        })
        // delAdmin(ids).then(() => {
        //   this.dialogPvVisible = false
        //   // this.list.splice(this.del_index, 1)
        //   this.getList()
        //   this.$notify({
        //     title: '成功',
        //     message: ' 解绑成功',
        //     type: 'success',
        //     duration: 4000
        //   })
        // })
      },

      // 搜索
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 批量选择
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

<style lang="scss">
  .conduct .conduct-input .el-button i {
    font-weight: 800;
  }

  .conduct .el-button--medium {
    padding: 0 20px !important;
  }

  .contetn .el-drawer.ltr,
  .el-drawer.rtl {
    height: 500px;
    top: 159px;
    // bottom: 100px;
    border-radius: 6px 0 0 6px;

    .el-drawer__close-btn {
      border: none !important;
      // border-color: #fff !important;
    }

    .el-drawer__header {
      margin-bottom: 10px !important;
    }
  }
</style>

<style lang="scss" scoped>
  $theme_text: #0F8BFD;
  $backg:rgba(0, 0, 0, 0);
  $deep_text: #5E5E5E;
  $theme_red: #ff5357;
  $theme_bg: #108CFD;
  $text_light: #CFCFD1;
  $text-deep2: #9298A7;

  .app-container {

    .content {
      background-color: #fff;
      padding: 0 15px;
      border-radius: 8px;
      position: relative;

      // 切换按钮
      .toggle-btn {
        cursor: pointer;
        height: 50px;
        display: flex;
        align-items: center;

        // background-color: antiquewhite;
        .toggle-btn-item {
          margin-right: 10px;
          height: 30px;
          width: 80px;
          text-align: center;
          line-height: 30px;
        }

        .isactive {
          color: #fff;
          background: linear-gradient(90deg, #1F99FE 0%, #01CAFD 100%);
          border-radius: 4px;
        }

        .disactive {
          color: $text-deep2;
        }
      }

      // 视频区
      .video {
        height: 520px;
        width: 100%;
        background-color: antiquewhite;
      }

      // 控制区
      .control {
        margin-top: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        // background-color: aqua;
        height: 98px;

        .screen-cut,
        .screen-btn,
        .screen-scale {
          margin-right: 20px;
        }

        .screen-cut {
          font-size: 14px;

          .screen-cut-item {
            cursor: pointer;
            color: $text_light;
            display: inline-block;
            padding: 0 5px;
            border: 1px solid $text_light;
            margin-right: 5px;
            border-radius: 3px;
            line-height: 25px;

            &:hover {
              color: $theme_bg;
              border-color: $theme_bg;
            }

            &:is-active {
              color: $theme_bg;
              border-color: $theme_bg;
            }
          }
        }

        .screen-btn {
          color: $theme_bg;
          border-radius: 50%;
          height: 98px;
          width: 98px;
          border: 3px solid $theme_bg;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: center;

          div {
            width: 100%;
            display: flex;
            justify-content: space-between;
          }

          .screen-btn-item {
            font-size: 23px;
            cursor: pointer;

            &:active {
              color: $theme_red;
            }
          }
        }

        .screen-scale {
          font-size: 15px;

          .screen-scale-item {
            cursor: pointer;
            display: inline-block;
            padding: 0 15px;
            border: 1px solid $text_light;
            margin-right: 5px;
            border-radius: 3px;
            line-height: 25px;
            color: $text_light;

            &:hover {
              color: $theme_bg;
              border-color: $theme_bg;
            }

            &:is-active {
              color: $theme_bg;
              border-color: $theme_bg;
            }
          }
        }
      }

      // 折叠 播放树
      .drawer-expand {
        // background-color: aquamarine;
        position: absolute;
        right: 0;
        top: 285px;

        .out-in {
          background-color: #fff;
          text-align: center;
          width: 40px;
          height: 55px;
          line-height: 55px;
          border-radius: 4px 0 0 4px;
          border: 2px solid $text_light;
          border-right: none;
          color: $text-deep2;
          font-size: 25px;
          font-weight: 800;
          cursor: pointer;
        }
      }

      .el-drawer {
        .drawer-title {
          // background-color: aquamarine;
          text-align: center;
          color: #9298A7;
          font-weight: 700;
          font-size: 21px;
          border-bottom: 1px solid $text_light;
          padding-bottom: 10px;
        }

        .drawer-con {
          // background-color: #faa;
          display: flex;
          justify-content: center;
        }
      }
    }

  }
</style>
